package com.tz.farmer.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.enums.ErrorCodeEnum;
import com.tz.farmer.mapper.BusinessInfoMapper;
import com.tz.farmer.mapper.CheckApplyMapper;
import com.tz.farmer.mapper.GoodsInfoMapper;
import com.tz.farmer.model.BusinessInfo;
import com.tz.farmer.model.CheckApply;
import com.tz.farmer.model.GoodsInfo;
import com.tz.farmer.service.WebDetectionApplyService;
import com.tz.farmer.so.CheckApplySo;
import com.tz.farmer.util.BeanConvertUtils;
import com.tz.farmer.util.ResultExM;
import com.tz.farmer.vo.CheckApplyVo;
import com.tz.farmer.vo.StatisticsExcleVo;
import com.tz.farmer.vo.StatisticsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class WebDetectionApplyServiceImpl extends ServiceImpl<CheckApplyMapper, CheckApply> implements WebDetectionApplyService {

    @Resource
    CheckApplyMapper checkApplyMapper;
    @Resource
    GoodsInfoMapper goodsInfoMapper;
    @Resource
    BusinessInfoMapper businessInfoMapper;

    @Override
    public ResultEx getDetectionApplyListConditions(CheckApplySo so) {

        if(ObjectUtils.isEmpty(so)
                || "".equals(so.getFlag())
                || "".equals(so.getCurrentPage())
                || so.getCurrentPage()==null
                || "".equals(so.getPageSize())
                || so.getPageSize() == null){
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
      /*  Page<CheckApply> page = (Page<CheckApply>) checkApplyMapper.selectPage(
                new Page<CheckApply>(so.getCurrentPage(), so.getPageSize()),
                new QueryWrapper<CheckApply>()
                        .eq("property", so.getFlag())
                        .eq(StringUtils.isNotEmpty(so.getClassify()),"check_type",so.getClassify())
                        .like(StringUtils.isNotEmpty(so.getKeyword()), "name", so.getKeyword())
                        .like(StringUtils.isNotEmpty(so.getKeyword()), "phone", so.getKeyword())
                        .last(StringUtils.isNotEmpty(so.getStartTime()),
                                " and 1= 1 and upload_time >= STR_TO_DATE( '"+so.getStartTime()+" 00:00:00','%Y-%m-%d %H:%i:%s')  and  upload_time <= STR_TO_DATE(' "+so.getEndTime()+ " 23:59:59','%Y-%m-%d %H:%i:%s')" )
                        .last( "   order by upload_time DESC "));
*/
        int total = checkApplyMapper.countFlag(so.getFlag(),so.getClassify(), so.getKeyword(), so.getStartTime(), so.getEndTime());
        int n = (so.getCurrentPage()-1)*so.getPageSize();
        int m =so.getPageSize();
        List<CheckApply> list = checkApplyMapper.selectConditionList(so.getFlag(),so.getClassify(), so.getKeyword(), so.getStartTime(), so.getEndTime(),n,m);
        if(CollectionUtils.isNotEmpty(list) && list.size() > 0){
            for (CheckApply checkApply:list) {
                    GoodsInfo goods = goodsInfoMapper.selectGoodsName(checkApply.getGoodsId());
                    if(!ObjectUtils.isEmpty(goods)){
                        checkApply.setProduct(goods.getGoodsName());
                    }
                    BusinessInfo businessInfo = businessInfoMapper.selectOne(new QueryWrapper<BusinessInfo>().eq("unisc_id", checkApply.getCheckName()));
                    if(!ObjectUtils.isEmpty(businessInfo)){
                        checkApply.setBusiness(businessInfo.getBusinessName());
                    }
            }
        }
        Map<String, Object> map = new Hashtable<>();
        map.put("total", total);
        map.put("data", list);
        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED, map);
    }

    @Override
    public ResultEx statisticsTopTen(CheckApplySo so) {

        Integer propertyOne = 0 ;
        Integer propertyTwo = 1 ;
        String typeOne ="当前商户";
        String typeTwo ="当前产品";
        if( so.getFlag() == null ) {
            String startTime = null;
            String endTime = null;
            List<StatisticsVo>   farmingBusiness = checkApplyMapper.selectBusiness(propertyOne,typeOne,startTime,endTime);
            List<StatisticsVo>   farmingProduct = checkApplyMapper.selectProduct(propertyOne ,typeTwo,startTime,endTime);
            List<StatisticsVo>   fishBusiness = checkApplyMapper.selectBusiness(propertyTwo,typeOne,startTime,endTime);
            List<StatisticsVo>   fishProduct= checkApplyMapper.selectProduct(propertyTwo ,typeTwo,startTime,endTime);
            Map<String , Object> map = new HashMap<>();
            map.put("farmingBusiness",farmingBusiness);
            map.put("farmingProduct",farmingProduct);
            map.put("fishBusiness",fishBusiness);
            map.put("fishProduct",fishProduct);
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,map);
        }else {
            if (0 == so.getFlag()) {
                List<StatisticsVo>   farmingBusiness = checkApplyMapper.selectBusiness(so.getFlag(),typeOne,so.getStartTime(),so.getEndTime());
                List<StatisticsVo>   farmingProduct = checkApplyMapper.selectProduct(so.getFlag() ,typeTwo,so.getStartTime(),so.getEndTime());
                Map<String , Object> map = new HashMap<>();
                map.put("farmingBusiness",farmingBusiness);
                map.put("farmingProduct",farmingProduct);
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,map);
            }
            if ( 1 == so.getFlag()) {
                List<StatisticsVo>   fishBusiness = checkApplyMapper.selectBusiness(so.getFlag(),typeOne,so.getStartTime(),so.getEndTime());
                List<StatisticsVo>   fishProduct= checkApplyMapper.selectProduct(so.getFlag() ,typeTwo,so.getStartTime(),so.getEndTime());
                Map<String , Object> map = new HashMap<>();
                map.put("fishBusiness",fishBusiness);
                map.put("fishProduct",fishProduct);
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,map);
            }
        }
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_FAIL);

    }

    @Override
    public List<CheckApplyVo> getDetectionApplyDownLoadList(CheckApplySo so) {

        List<CheckApplyVo> listVo = new ArrayList<>();
        List<CheckApply> list = checkApplyMapper.selectDownLoadList(so.getFlag(),so.getClassify(), so.getKeyword(), so.getStartTime(), so.getEndTime(),so.getIds());

        if(CollectionUtils.isNotEmpty(list) || list.size() > 0){
            for ( int i = 0 ; i<list.size() ; i++) {

                CheckApplyVo checkApplyVo = BeanConvertUtils.copyProperties(list.get(i), CheckApplyVo.class);
                LocalDateTime createTime = list.get(i).getUploadTime();
                DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                checkApplyVo.setUploadTime(sf.format(createTime));
                GoodsInfo goods = goodsInfoMapper.selectOne(new QueryWrapper<GoodsInfo>().eq("goods_id", list.get(i).getGoodsId()));
                if(!ObjectUtils.isEmpty(goods)){
                    checkApplyVo.setProduct(goods.getGoodsName());
                }
                BusinessInfo businessInfo = businessInfoMapper.selectOne(new QueryWrapper<BusinessInfo>().eq("unisc_id", list.get(i).getCheckName()));
                if(!ObjectUtils.isEmpty(businessInfo)){
                    checkApplyVo.setBusiness(businessInfo.getBusinessName());
                }
                listVo.add(checkApplyVo);
            }
        }
        if(CollectionUtils.isEmpty(listVo) || listVo.size() < 0){
            return new ArrayList<>();
        }
        return  listVo;
    }

    @Override
    public List<StatisticsExcleVo> getstatisticsDownLoadList(CheckApplySo so) {
        log.info("flag"+so.getFlag());
        String typeOne ="当前商户";
        String typeTwo ="当前产品";
        List<StatisticsVo>   business = new ArrayList<>();
        List<StatisticsExcleVo>   exl = new ArrayList<>();
        if("1".equals(so.getDoFlag())){ //商家 param : doflag = 1   flag = 0 | 1  time
            business= checkApplyMapper.selectBusiness(so.getFlag(),typeOne,so.getStartTime(),so.getEndTime());
            log.info("business1111:========>>>>>>"+business);
        }
        if("2".equals(so.getDoFlag())){ //产品
            business = checkApplyMapper.selectProduct(so.getFlag() ,typeTwo,so.getStartTime(),so.getEndTime());
            log.info("business22222:========>>>>>>"+business);
        }
        if(CollectionUtils.isNotEmpty(business) || business.size() > 0){
            for ( int i = 0 ; i<business.size() ; i++) {
                StatisticsExcleVo statisticsExcleVo = BeanConvertUtils.copyProperties(business.get(i), StatisticsExcleVo.class);
              /*  LocalDateTime createTime = business.get(i).getUploadTime();
                  DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                  statisticsExcleVo.setUploadTime(sf.format(createTime));
                */
                statisticsExcleVo.setUploadTime(so.getStartTime() +" - "+so.getEndTime());
                exl.add(statisticsExcleVo);
            }
        }
        return exl;
    }



}
